#!/usr/bin/env python3
"""
JavaScript代码执行器测试用例
包含基础功能测试和安全风险测试
"""

import asyncio
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from base_test import BaseCodeSandboxTest

class TestJavaScriptExecutor(BaseCodeSandboxTest):
    """JavaScript代码执行器测试类"""
    
    def __init__(self):
        super().__init__()
        self.code_type = "javascript"
    
    async def test_basic_functionality(self):
        """测试JavaScript基础功能"""
        print("🟨 测试JavaScript基础功能...")
        
        test_cases = [
            {
                "name": "基础输出",
                "code": "console.log('Hello, JavaScript!');\nconsole.log('测试中文输出');",
                "security_level": "low",
                "expected_output": ["Hello, JavaScript!", "测试中文输出"]
            },
            {
                "name": "数学计算",
                "code": "const result = Math.PI * 2;\nconsole.log(`2π = ${result.toFixed(4)}`);",
                "security_level": "low",
                "expected_output": ["2π = 6.2832"]
            },
            {
                "name": "循环和条件",
                "code": """
for (let i = 0; i < 5; i++) {
    if (i % 2 === 0) {
        console.log(`${i} is even`);
    } else {
        console.log(`${i} is odd`);
    }
}
""",
                "security_level": "low",
                "expected_output": ["0 is even", "1 is odd", "2 is even", "3 is odd", "4 is even"]
            },
            {
                "name": "数组操作",
                "code": """
const numbers = [1, 2, 3, 4, 5];
const squares = numbers.map(x => x * x);
console.log(squares);
""",
                "security_level": "low",
                "expected_output": ["[ 1, 4, 9, 16, 25 ]"]
            },
            {
                "name": "字符串处理",
                "code": """
const text = "Hello World";
console.log(text.toUpperCase());
console.log(text.toLowerCase());
console.log(text.replace("World", "JavaScript"));
""",
                "security_level": "low",
                "expected_output": ["HELLO WORLD", "hello world", "Hello JavaScript"]
            },
            {
                "name": "JSON操作",
                "code": """
const obj = { name: "测试", age: 25, active: true };
const jsonStr = JSON.stringify(obj);
console.log(jsonStr);
const parsed = JSON.parse(jsonStr);
console.log(parsed.name);
""",
                "security_level": "low",
                "expected_output": ["测试"]
            }
        ]
        
        for case in test_cases:
            await self.run_test_case(case)
    
    async def test_error_handling(self):
        """测试JavaScript错误处理"""
        print("🟨 测试JavaScript错误处理...")
        
        error_cases = [
            {
                "name": "语法错误",
                "code": "console.log('missing quote);",
                "security_level": "low",
                "expect_error": True
            },
            {
                "name": "运行时错误",
                "code": "console.log('Before error');\nthrow new Error('测试错误');\nconsole.log('After error');",
                "security_level": "low",
                "expect_error": True,
                "expected_output": ["Before error"]
            },
            {
                "name": "引用错误",
                "code": "console.log(undefinedVariable);",
                "security_level": "low",
                "expect_error": True
            },
            {
                "name": "类型错误",
                "code": "const num = null;\nconsole.log(num.toString());",
                "security_level": "low",
                "expect_error": True
            }
        ]
        
        for case in error_cases:
            await self.run_test_case(case)
    
    async def run_all_tests(self):
        """运行所有JavaScript测试"""
        print("🚀 开始JavaScript代码执行器完整测试...")
        
        try:
            await self.test_basic_functionality()
            await self.test_error_handling()
            
            print("✅ JavaScript测试全部完成!")
            return True
            
        except Exception as e:
            print(f"❌ JavaScript测试失败: {e}")
            return False

async def main():
    """主函数"""
    tester = TestJavaScriptExecutor()
    success = await tester.run_all_tests()
    return success

if __name__ == "__main__":
    success = asyncio.run(main())
    exit(0 if success else 1) 